<?php

namespace App\Models\Admin;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;


class Admin extends Authenticatable
{
    use Notifiable;

    protected $rememberTokenName = 'rememberToken';

    protected $table = 'admin';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name' , 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * 用户角色
     * @return [type] [description]
     */
    public function roles(){
        return $this->belongsToMany(Role::class,'role_admin','admin_id','role_id');
    }

    /**
     * 用户信息
     * @return [type] [description]
     */
    public function info(){
        return $this->hasOne('App\Models\Admin\Info');
    }

    /**
     * 验证用户具有某权限
     * @param  [type]  $permission [description]
     * @return boolean             [description]
     */
    public function hasPermission($permission){
        if(is_string($permission)){
            $permission = Permission::where('name',$permission)->first();
            if(!$permission){return false;}
        }
        
        return $this->hasRole($permission->roles);
    }

    /**
     * 用户是否具有某角色
     * @param  [type]  $role [description]
     * @return boolean       [description]
     */
    public function hasRole($role){
        if (is_string($role)) {
            return $this->roles->contains('name', $role);
        }
        return !!$role->intersect($this->roles)->count();
    }
}
